import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;

public class WorkerMachine implements Runnable{
	
	Socket workerSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	//String command;
	String name;
	String logfile_name;
	int port;
	
	public WorkerMachine( String name, int port ) {
		this.name = name;
		this.port = port;
		logfile_name = name + ".log";
		
	}
	
	public Object ProcessCommand(String command) {
		if(command.equals("shutdown"))
			return null;
		Object ret = null;
		if(command.startsWith("grep"))
		{
			//This exec code block pulled from a forum post on ubuntuforums.org (/archive/index.php/t-319735.html)
			try {
				
				Process proc = Runtime.getRuntime().exec(command + " " + logfile_name);
				BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
				try {
					proc.waitFor();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				ret = new ArrayList<String>();
				while(br.ready()) {
					String l = br.readLine();
					((ArrayList<String>)ret).add(l);
					//System.out.println("Search request found: " + l);
				}
				return ret;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(command.equals("log"))
		{
			
		}
		
		return ret;
		
		
	}
	
	public void run() {
		try {
			//http://linux-v1.ews.illinois.edu
			workerSocket = new Socket("192.17.11.10", port);
			System.out.println("connected");
			
			out = new ObjectOutputStream(workerSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(workerSocket.getInputStream());
			Object message = null;
			do {
				try {
					message = in.readObject();
					if(message instanceof ArrayList<?>) {
						System.out.println("Output: " + ((ArrayList<String>)(message)).toString()); 
					}
					if(message instanceof String) {
						System.out.println("Command received: " + (String)message);
						SendObject(ProcessCommand((String)message));
					}
					
					
					
				} catch (ClassNotFoundException e) {
					System.out.println("Unknown data type");
				}
			} while(!message.equals("shutdown"));
			
			
			
			
		} catch (IOException exc) {
			exc.printStackTrace();
		}
	}
	
	public void SendObject( Object obj ) {
		try {
			out.writeObject(obj);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void WriteLog(String key, String value) {
		try {
			File file = new File(name+".log");
			if(!file.exists()) {
				file.createNewFile();
			}
			
			FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
			BufferedWriter bw = new BufferedWriter(fw);
			PrintWriter pw = new PrintWriter(bw);
			pw.println(key + " : " + value);
			pw.close();
			
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

	public static void main(String[] args) {
		WorkerMachine m1 = new WorkerMachine("machine.1", 2413);
		//m1.WriteLog("INFO", "hello wored");
		Thread worker_thread = new Thread(m1);
		worker_thread.start();
		
		Scanner in = new Scanner(System.in);
        //request forever for a more grep commands
        while(true){
            String grep = in.nextLine();
            String message = "";
            if (grep.contains("-key")){
                message = grep.substring(10);
                System.out.println("grep -n -P "+message + ".*(?=:)");
                m1.SendObject("grep -n -P "+message + ".*(?=:)");
                //m1.ProcessCommand("grep -n -P (?<=:) "+ message+".*");
            }
            else if (grep.contains("-value")){
                message = grep.substring(12);
                System.out.println("grep -n -P (?<=:) "+ message+".*");
                m1.SendObject("grep -n -P (?<=:) "+ message+".*");
                //m1.ProcessCommand("grep -n -P (?<=:) "+ message+".*");
            }
            else {
            	message = grep.substring(4);
            	System.out.println("grep " + message);
            	m1.SendObject("grep -n "+ message);
            	//m1.ProcessCommand("grep "+ message);
            }
        }
		//m1.ProcessCommand("grep -P INFO.*(?=:)");

	}


}
